<template>
  <van-pull-refresh
    class="c-list-refresh"
    ref="refreshRef"
    v-model="refreshing"
    :disabled="refreshDisabled"
    @refresh="onRefresh">
    <van-list
      class="c-list"
      ref="listRef"
      :immediate-check="immediateCheck"
      v-model="loading"
      loading-text="加载中..."
      :finished="finished"
      finished-text="~没有更多了"
      :error.sync="error"
       error-text="请求失败，点击重新加载"
      @load="onLoad"
      @scroll.native="onScroll">
      <slot></slot>
    </van-list>
  </van-pull-refresh>
</template>

<script>
import { PullRefresh as VanPullRefresh, list as VanList } from 'vant'

// 下拉刷新禁用检测距离
const RefreshDisabledOffset = 20

export default {
  name: 'list',
  components: {
    VanPullRefresh,
    VanList
  },
  props: {
    immediateCheck: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      refreshing: false,
      refreshDisabled: false,
      loading: false,
      finished: false,
      error: false
    }
  },
  methods: {
    async onRefresh () {
      this.finished = false
      this.loading = true
      this.$emit('refresh', this.done)
    },
    async onLoad () {
      this.$emit('load', this.done)
    },
    done (state) {
      if (this.refreshing) {
        this.refreshing = false
      }
      this.loading = false
      // 处理异常状态
      if (state === 'finished') {
        this.finished = true
      } else if (state === 'failed') {
        this.error = true
      }
    },
    onScroll (event) {
      if (!event) return
      this.$emit('scroll', event)
      // 更新 refreshDisabled
      const el = event.target
      if (el.scrollTop > RefreshDisabledOffset) {
        this.refreshDisabled = true
      } else {
        this.refreshDisabled = false
      }
    },
    scrollTo (y) {
      const { listRef } = this.$refs
      const listEl = listRef && listRef.$el
      listEl && listEl.scrollTo(0, y)
    },
    reset () {
      this.refreshing = false
      this.refreshDisabled = false
      this.loading = false
      this.finished = false
      this.error = false
    },
    check () {
      const { listRef } = this.$refs
      listRef && listRef.check()
    }
  },
  created () {
    this.done = this.done.bind(this)
  }
}
</script>

<style lang="less">
.c-list-refresh {
  &.van-pull-refresh {
    height: 100%;
  }
}

.c-list {
  &.van-list {
    height: 100%;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }
}
</style>
